﻿// See https://aka.ms/new-console-template for more information
using IdentityModel.Client;

//IdentityServer4 - 客户端凭据许可（通过第三方的ID和密钥获取Token）

#region 获取token

var client = new HttpClient();

var disco = await client.GetDiscoveryDocumentAsync("https://localhost:4000");

if (disco.IsError)
{
    Console.WriteLine(disco.Error);
    return;
}

//客户端模式
//var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
//{
//    Address = disco.TokenEndpoint,
//    ClientId = "Harris_ClientID",
//    ClientSecret = "Harris123456"
//});

//资源拥有者凭据（username or password)
var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
    Address = disco.TokenEndpoint,
    ClientId = "Harris_Client_Pass_ID",
    ClientSecret = "Harris123456",
    UserName = "user1",
    Password = "Test_123"
});

if (tokenResponse.IsError)
{
    Console.WriteLine(disco.Error);
    return;
}

Console.WriteLine(tokenResponse.Json);

#endregion

#region 使用token

var apiclient = new HttpClient();

apiclient.SetBearerToken(tokenResponse.AccessToken);

var response = await apiclient.GetAsync("https://localhost:5013/api/Users/GetSearch?pageIndex=1&PageSize=10");

if (!response.IsSuccessStatusCode)
{
    Console.WriteLine(response.StatusCode);

    return;
}

string result = await response.Content.ReadAsStringAsync();

#endregion

Console.WriteLine(result);
//Console.WriteLine(JArray.Parse(result));

Console.ReadLine();